package com.wolfsea.binderdemo
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import com.wolfsea.binderdemo.databinding.ActivityMainBinding

class MainActivity : BaseActivity<ActivityMainBinding>(ActivityMainBinding::inflate) {

    //private var numberStub: CalculateNumberStub? = null
    //private var numberProxy: CalculateNumberProxy? = null
    private var calculateNumber: ICalculateNumber? = null

    override fun init(savedInstanceState: Bundle?) {

        bindService(Intent().apply {
            setClassName(
                "com.wolfsea.binderdemo",
                "com.wolfsea.binderdemo.CalculateNumberService"
            )
        }, serviceConnection, Context.BIND_AUTO_CREATE)

        mBinding.btnAdd.setOnClickListener {
            val result = calculateNumber?.doSum(10, 5)
            Log.d(TAG, "result:${result}")
        }

        mBinding.btnMinus.setOnClickListener {
            val result = calculateNumber?.doMinus(10, 5)
            Log.d(TAG, "result:${result}")
        }

        mBinding.btnKillPid.setOnClickListener {
            val pid = calculateNumber?.getPid()
            Log.d(TAG, "pid:${pid}")
            android.os.Process.killProcess(pid!!)
        }
    }

    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            //numberStub = CalculateNumberStub.asInterface(service) as CalculateNumberStub
            //numberProxy = CalculateNumberStub.asInterface(service) as CalculateNumberProxy
            calculateNumber = CalculateNumberStub.asInterface(service)
            Log.d(TAG, "onServiceConnected")
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            //numberStub = null
            //numberProxy = null
            calculateNumber = null
            Log.d(TAG, "onServiceDisconnected")
        }
    }

    companion object {
        const val TAG = "MainActivity"
    }
}